import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import Login from "./user/login.vue";
import axios from "axios";
import User from "./user/index.vue";
import Layout from "./layout/index.vue";
import Carousel from "./carousel/index.vue";
import Upload from "./carousel/upload.vue";

Vue.use(ElementUI);

const instance = axios.create({
	baseURL: "http://localhost:9000",
});

instance.defaults.headers.post["Content-Type"] = "application/json";
instance.defaults.headers.common["authorization"] = `${sessionStorage.getItem(
	"token"
)}`;

Vue.prototype.$axios = instance;

Vue.use(VueRouter);
const router = new VueRouter({
	routes: [
		{ path: "/login", name: "login", component: Login },
		{
			path: "/",
			component: Layout,
			children: [
				{ path: "/users", name: "users", component: User },
				{ path: "/carousel", name: "carousel", component: Carousel },
				{ path: "/upload", name: "upload", component: Upload },
			],
		},
	],
});

router.beforeEach((to, from, next) => {
	const isAuthenticated = sessionStorage.getItem("token");
	if (to.name !== "login" && !isAuthenticated) next({ name: "login" });
	else next();
});

new Vue({
	router,
	render: h => h(App),
}).$mount("#app");
